package com.powernode.rules.service.impl;

import com.alibaba.fastjson.JSON;
import com.powernode.model.form.rules.ProfitSharingRuleRequest;
import com.powernode.model.form.rules.ProfitSharingRuleRequestForm;
import com.powernode.model.vo.rules.ProfitSharingRuleResponse;
import com.powernode.model.vo.rules.ProfitSharingRuleResponseVo;
import com.powernode.rules.config.DroolsHelper;
import com.powernode.rules.service.ProfitSharingRuleService;
import lombok.extern.slf4j.Slf4j;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class ProfitSharingRuleServiceImpl implements ProfitSharingRuleService {
    @Override
    public ProfitSharingRuleResponseVo calculateOrderProfitSharingFee(ProfitSharingRuleRequestForm profitsharingRuleRequestForm) {
        // 封装传入对象
        ProfitSharingRuleRequest profitSharingRuleRequest = new ProfitSharingRuleRequest();
        profitSharingRuleRequest.setOrderAmount(profitsharingRuleRequestForm.getOrderAmount());
        profitSharingRuleRequest.setOrderNum(profitsharingRuleRequestForm.getOrderNum());
        log.info("传入参数：{}", JSON.toJSONString(profitSharingRuleRequest));
        // 获取最新订单费用规则
        KieSession kieSession = DroolsHelper.loadForRule("rules/ProfitsharingRule.drl");
        // 封装返回对象
        ProfitSharingRuleResponse profitSharingRuleResponse = new ProfitSharingRuleResponse();
        kieSession.setGlobal("profitSharingRuleResponse", profitSharingRuleResponse);
        // 设置订单对象
        kieSession.insert(profitSharingRuleRequest);
        // 触发规则
        kieSession.fireAllRules();
        // 中止会话
        kieSession.dispose();
        log.info("计算结果：{}", JSON.toJSONString(profitSharingRuleResponse));
        // 封装返回对象
        ProfitSharingRuleResponseVo profitsharingRuleResponseVo = new ProfitSharingRuleResponseVo();
        profitsharingRuleResponseVo.setProfitSharingRuleId(1L);
        BeanUtils.copyProperties(profitSharingRuleResponse, profitsharingRuleResponseVo);
        return profitsharingRuleResponseVo;
    }
}